package wsi.detect;

import org.rygh.core.util.timer.TaskTime;
import org.rygh.semantic.gui.swing.input.Input;

import wsi.dataguide.tree.WSXmlParser;
import wsi.function.Function;
import wsi.match.Matcher;
import wsi.match.SubtreeMatch;
import wsi.subgraph.tree.EntityTree;

public class DetectHelper {

	private final Matcher matcher = new Matcher();
	private TaskTime timer;
	private boolean cacheWhatever = false;
	private boolean saveInputFile = true;

	public DetectHelper() {

	}

	public SubtreeMatch detect(Input input, EntityTree entityTree, String xml) {
		if (xml == null || entityTree == null)
			return null;

		return matcher.match(input, entityTree, xml);
	}

	public SubtreeMatch detect(Input input, Function function, String xml) {
		return detect(input, prepareTree(input, function), xml);
	}

	public String prepareHtml(Input input, Function function) {
		Caller caller = new Caller(function);
		caller.setCacheWhatever(cacheWhatever);
		caller.setSaveInputFile(saveInputFile);

		// System.out.println("  begin to call " + input);

		timer.start();
		String html = caller.call(input);
		timer.end();

		html = caller.postprocess(html);

		// System.out.println("  end calling, obtained "
		// + (html == null ? 0 : html.length()));

		return WSXmlParser.checkValid(input, html);
	}

	public EntityTree prepareTree(Input input, Function function) {
		return matcher.prepareEntityTree(input, function);
	}

	public void setCacheWhatever(boolean cacheWhatever) {
		this.cacheWhatever = cacheWhatever;
	}

	public void setSaveInputFile(boolean saveInputFile) {
		this.saveInputFile = saveInputFile;
	}

	public void setTimer(TaskTime timer) {
		this.timer = timer;
	}

}
